package com.kanq.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kanq.common.utils.CommonUtils;
import com.kanq.pojo.entity.KanqAiHistory;
import com.kanq.pojo.entity.KanqAiHistoryAnswer;
import com.kanq.pojo.entity.KanqAiHistoryQuestion;
import com.kanq.pojo.response.HistoryConversation;
import com.kanq.service.KanqAiHistoryAnswerService;
import com.kanq.service.KanqAiHistoryQuestionService;
import com.kanq.service.KanqAiHistoryService;
import com.kanq.tool.R;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/history")
public class HistoryController {

    @Resource
    private KanqAiHistoryService kanqAiHistoryService;

    @Resource
    private KanqAiHistoryQuestionService kanqAiHistoryQuestionService;

    @Resource
    private KanqAiHistoryAnswerService kanqAiHistoryAnswerService;

    /**
     * 获取历史记录列表
     */
    @GetMapping("/getHistoryPage")
    public R getHistoryPage(@RequestParam String userId, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
        IPage<KanqAiHistory> page = kanqAiHistoryService.selectAllPage(new Page<>(pageNum, pageSize), userId);
        return R.data(page);
    }


    /**
     * 获取会话历史消息
     */
    @GetMapping("/getHistoryConversationData")
    public R getHistoryConversationData(@RequestParam String userId, @RequestParam String conversationId) {
        List<HistoryConversation> historyConversationList = kanqAiHistoryService.getHistoryConversationData(userId, conversationId);
        return R.data(historyConversationList);
    }

    /**
     * 处理POST请求，更新会话历史标题
     */
    @PostMapping("/update")
    public R update(@RequestBody KanqAiHistory kanqAiHistory) {
        return R.status(kanqAiHistoryService.updateById(kanqAiHistory));
    }

    /**
     * 删除会话接口
     */
    @PostMapping("/remove")
    public R remove(@RequestParam String ids) {
        boolean a = kanqAiHistoryService.removeByIds(CommonUtils.idsStrToListSeparator(ids, ","));
        /**先查询出问题的id*/
        List<KanqAiHistoryQuestion> list = kanqAiHistoryQuestionService.list(Wrappers.<KanqAiHistoryQuestion>lambdaQuery().in(KanqAiHistoryQuestion::getHistoryId, CommonUtils.idsStrToListSeparator(ids, ",")));
        List<Long> questionIds = list.stream().map(KanqAiHistoryQuestion::getHistoryQuestionId).toList();
        boolean c = kanqAiHistoryAnswerService.remove(Wrappers.<KanqAiHistoryAnswer>lambdaQuery().in(KanqAiHistoryAnswer::getHistoryQuestionId, questionIds));
        boolean b = kanqAiHistoryQuestionService.remove(Wrappers.<KanqAiHistoryQuestion>lambdaQuery().in(KanqAiHistoryQuestion::getHistoryId, CommonUtils.idsStrToListSeparator(ids, ",")));
        return R.status(a & b & c);
    }

}
